package com.example.wxsmart.resources;

import com.example.wxsmart.dto.request.ElasticSearchCreateIndexRequest;
import com.example.wxsmart.util.Result;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.IOException;

/**
 * @author Luojunxian
 * @data 2022/5/31 10:43
 * @classname ElasticSearchIndexResources
 */
@Slf4j
@Component
public class ElasticSearchIndexResources {

    @Resource
    private RestHighLevelClient client;

    /**
     * 创建索引
     *
     * @param request 请求
     */
    public void createIndex(ElasticSearchCreateIndexRequest request) {
        // 创建index索引请求
        CreateIndexRequest createIndexRequest = new CreateIndexRequest(request.getIndex());

        // 传入请求参数,DLS
        createIndexRequest.source(request.getSource().toString(), XContentType.JSON);

        // 发起请求
        try {
            client.indices().create(createIndexRequest, RequestOptions.DEFAULT);

            log.info("ElasticSearch:{}索引创建成功!", request.getIndex());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 删除索引
     *
     * @param index 指数
     */
    public void deleteIndex(String index) {
        DeleteIndexRequest deleteIndexRequest = new DeleteIndexRequest(index);

        try {
            client.indices().delete(deleteIndexRequest, RequestOptions.DEFAULT);

            log.info("ElasticSearch:{}索引删除成功!", index);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 判断索引是否存在
     *
     * @param index 指数
     * @return {@code Result<Boolean>}
     */
    public Result<Boolean> existsIndex(String index) {
        GetIndexRequest getIndexRequest = new GetIndexRequest(index);

        boolean result = false;

        try {
            result = client.indices().exists(getIndexRequest, RequestOptions.DEFAULT);

            log.info("ElasticSearch:{}索引是否存在:{}", index, result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.ok(result);
    }
}
